package com.hmdp.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisIdWorker {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final long BEGIN_TIMESTAMP = 1640995200L;

    public long nextId(String keyPrefix) {
        // 1.生成时间戳
        //得到当前时间
        LocalDateTime localDateTime = LocalDateTime.now();
        //得到秒
        long second = localDateTime.toEpochSecond(ZoneOffset.UTC);
        //减去开始时间
        long timestamp = second - BEGIN_TIMESTAMP;

        // 2.获取当前 序列号
        //获取当前日期
        String date = localDateTime.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + date);

        // 3.拼接
        return timestamp << 32 | count;
    }

}
